package com.atguigu.gulimall.order.web;

import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.OrderConfirmVo;
import com.atguigu.gulimall.order.vo.OrderSubmitVo;
import com.atguigu.gulimall.order.vo.SubmitOrderResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.concurrent.ExecutionException;

/**
 * 结算页面
 *
 * @author LaiSanShan
 * @date 2021-08-31
 */
@Controller
public class OderWebController {

    @Autowired
    OrderService orderService;

    /**
     * 去订单结算页
     *
     * @param model 模型
     * @return 结算页面
     * @throws ExecutionException   异步编排的异常
     * @throws InterruptedException 异步编排的异常
     */
    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = orderService.confirmOrder();

        model.addAttribute("orderConfirmData", confirmVo);
        return "confirm";
    }

    /**
     * 提交订单到收银页
     *
     * @return 收银页
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo vo, Model model, RedirectAttributes redirectAttributes) {
        SubmitOrderResponseVo responseVo = orderService.submitOrder(vo);
        if (responseVo.getCode() == 0) {
            // 成功
            model.addAttribute("submitOrderResp", responseVo);
            return "pay";
        } else {
            // 失败
            if (responseVo.getCode() == 1) {
                redirectAttributes.addFlashAttribute("msg", "订单信息过期，请刷新再提交");
            } else if (responseVo.getCode() == 2) {
                redirectAttributes.addFlashAttribute("msg", "订单商品价格发送变化，请确认后提交");
            } else if (responseVo.getCode() == 3) {
                redirectAttributes.addFlashAttribute("msg", "库存锁定失败，商品库存不足");
            }
            return "redirect:http://order.gulimall.com/toTrade";
        }
    }

}
